package com.rain.shoppingscienceproj.ui.activity.shopping;

import android.Manifest;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rain.shoppingscienceproj.R;
import com.rain.shoppingscienceproj.http.BaseSubscriber;
import com.rain.shoppingscienceproj.http.ExceptionHandle;
import com.rain.shoppingscienceproj.http.RetrofitClient;
import com.rain.shoppingscienceproj.module.CarData;
import com.rain.shoppingscienceproj.module.GoodsDto;
import com.rain.shoppingscienceproj.module.MainData;
import com.rain.shoppingscienceproj.module.Shop;
import com.rain.shoppingscienceproj.module.ShoppingcarDto;
import com.rain.shoppingscienceproj.ui.activity.BaseActivity;
import com.rain.shoppingscienceproj.ui.activity.login.LoginActivity;
import com.rain.shoppingscienceproj.ui.activity.order.MakeOrderActivity;
import com.rain.shoppingscienceproj.ui.activity.store.StoreListActivity;
import com.rain.shoppingscienceproj.ui.adapter.DetaileImageAdapter;
import com.rain.shoppingscienceproj.ui.base.GlobalData;
import com.rain.shoppingscienceproj.ui.utile.DialogUtils;
import com.rain.shoppingscienceproj.ui.utile.TitleUtils;
import com.rain.shoppingscienceproj.ui.utile.TypeData;
import com.rain.shoppingscienceproj.utils.AppManager;
import com.rain.shoppingscienceproj.utils.ImageUtils;
import com.rain.shoppingscienceproj.utils.LoadingDialog;
import com.rain.shoppingscienceproj.utils.ToolPhone;
import com.rain.shoppingscienceproj.utils.Util;
import com.rain.shoppingscienceproj.utils.layoutmanager.CustomLinearLayoutManager;
import com.rain.shoppingscienceproj.utils.toast.ToastUtils;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 商品详情
 */
public class ShoppingDetailsActivity extends BaseActivity {

    private IWXAPI api;
    private static final String APP_ID = "wx1667701a1c1857aa";
    private String shopping;
    private int index;//获取视频的下标
    @BindView(R.id.banner)
    ImageView bannerView;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.tv_shop_title)
    TextView tv_shop_title;//标题
    @BindView(R.id.tv_share)
    TextView tv_share;//分享
    @BindView(R.id.tv_expressage)
    TextView tv_expressage;//快递
    @BindView(R.id.tv_sales_volume)
    TextView tv_sales_volume;//销量
    @BindView(R.id.tv_address)
    TextView tv_address;//地址
    @BindView(R.id.tv_stock)
    TextView tv_stock;
    @BindView(R.id.tv_specification)
    TextView tv_specification;//规格
    @BindView(R.id.tv_evaluate)
    TextView tv_evaluate;//评价數量
    @BindView(R.id.iv_photo_user)
    ImageView iv_photo_user;//评论人的头像
    @BindView(R.id.tv_user_name)
    TextView tv_user_name;//评论人的name
    @BindView(R.id.tv_content)
    TextView tv_content;//评论内容
    @BindView(R.id.iv_store_image)
    ImageView iv_store_image;//店铺图片
    @BindView(R.id.tv_store_title)
    TextView tv_store_title;//店铺标题
    @BindView(R.id.ll_comment)
    LinearLayout ll_comment;
    @BindView(R.id.iv_image)
    ImageView iv_image;
    @BindView(R.id.tv_is_no_comment)
    TextView tv_is_no_comment;
    @BindView(R.id.iv_image_music)
    ImageView iv_image_music;
    @BindView(R.id.tv_context)
    TextView tv_context;
    @BindView(R.id.rv_data)
    RecyclerView rv_data;
    private GoodsDto goodsData;
    private MediaPlayer mediaPlayer;
    DetaileImageAdapter adapter;

    ObjectAnimator animator = null;

    private List<MainData> list = TypeData.getData();


    private boolean isPlayer = true, isOpen = false, isPans = true;
    private int mTargetScene = SendMessageToWX.Req.WXSceneSession;
    private int num = 1;
    private TextView tv_num;
    private Animation operatingAnim;

    @OnClick(R.id.ll_comment)
    void comment() {
        startActivitys(CommentDetailActivity.class, goodsData.getGoods().getGoodsId());
    }

    @OnClick(R.id.iv_image_music)
    void musicStop() {
        if (!isOpen) {
            ToastUtils.showShortToast("该商品没有音乐");
            return;
        }
        //如果在播放中，立刻暂停。
        if (isPlayer) {
            isPlayer = false;
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
//                iv_image.setImageResource(R.drawable.muse_pree);
//                iv_image_music.clearAnimation();
                isPans = false;
                animator.end();
            }
        } else {
            isPlayer = true;
            if (!mediaPlayer.isPlaying()) {
                mediaPlayer.start();
                isPans = true;
                animator.start();
//                iv_image_music.startAnimation(operatingAnim);
//                iv_image.setImageResource(R.drawable.muse_no);
            }
        }
    }

    @OnClick(R.id.tv_share)
    void share() {
        showDialog();
    }

    private void showDialog() {
        View v = getLayoutInflater().inflate(R.layout.layout_share, null);
        final Dialog dialog = new Dialog(this, R.style.MyDialog);
        WindowManager wm = getWindowManager();
        int mHeight = wm.getDefaultDisplay().getHeight();
        int mWeight = wm.getDefaultDisplay().getWidth();
        dialog.setContentView(v, new WindowManager.LayoutParams(mWeight, ((mHeight * 2) / 3)));
        LinearLayout ll_wx_wechat = v.findViewById(R.id.ll_wx_wechat);
        LinearLayout ll_wx_moments = v.findViewById(R.id.ll_wx_moments);
        ll_wx_wechat.setOnClickListener(view -> shareUrl(1, dialog));
        ll_wx_moments.setOnClickListener(view -> shareUrl(2, dialog));
        Window window = dialog.getWindow();
        // 显示动画
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        dialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }


    private void shareUrl(int i, Dialog dialog) {
        dialog.dismiss();
        switch (i) {
            case 1:
                mTargetScene = SendMessageToWX.Req.WXSceneSession;
                wxShare();
                break;

            case 2:
                mTargetScene = SendMessageToWX.Req.WXSceneTimeline;
                wxShare();
                break;
        }
    }

    private void wxShare() {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = "http://www.baidu.com";
        WXMediaMessage msg;
        msg = new WXMediaMessage(webpage);
        msg.title = goodsData.getGoods().getGoodsName();
        msg.description = goodsData.getGoods().getGoodsName();
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.share_icon);
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 150, 150, true);
        bmp.recycle();
        msg.thumbData = Util.bmpToByteArray(thumbBmp, true);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = mTargetScene;
        api.sendReq(req);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        shopping = getIntent().getStringExtra("type");
        setContentView(R.layout.activity_shopping_details);
        AppManager.getAppManager().addActivity(this);
        ButterKnife.bind(this);
        TitleUtils.TitleView(this, "商品详情");
        api = WXAPIFactory.createWXAPI(this, APP_ID, true);
        api.registerApp(APP_ID);
        loadingDialog = new LoadingDialog(this, "正在加载...");
        userInfo = GlobalData.getUserInfo();
        rv_data.setLayoutManager(new CustomLinearLayoutManager(this));
        adapter = new DetaileImageAdapter(this);
        rv_data.setAdapter(adapter);
        initView();
        initData();
        initListener();
    }

    private void initView() {
    }


    private void initMediaPlayer(String url) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {
            mediaPlayer = new MediaPlayer();
            try {
                mediaPlayer.setDataSource(url);
//            mediaPlayer.prepareAsync() ;
                mediaPlayer.setLooping(true);//设置为循环播放
                mediaPlayer.prepare();//初始化播放器MediaPlayer
                if (!mediaPlayer.isPlaying()) {
                    mediaPlayer.start();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    private void initData() {
        loadingDialog.show();
        RetrofitClient.getInstance(this)
                .createBaseApi()
                .goodsDetaile(shopping, new BaseSubscriber<GoodsDto>(this) {
                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable e) {
                        ToastUtils.showShortToast(e.Message);
                        loadingDialog.dismiss();
                    }

                    @Override
                    public void onNext(GoodsDto goods) {
                        super.onNext(goods);
                        goodsData = goods;
                        if (goods.getGoods().getImages() != null && !"".equals(goods.getGoods().getImages())) {
                            if (goods.getGoods().getImages().contains(",")) {
                                String[] str = goods.getGoods().getImages().split(",");
                                adapter.setParticulars(str);
                            }
                        }
                        ImageUtils.image(ShoppingDetailsActivity.this, goods.getGoods().getGoodsImage(), bannerView);
                        tv_money.setText(Double.valueOf(goods.getGoods().getGoodsPay()) / 100 + "");
                        tv_shop_title.setText(goods.getGoods().getGoodsName());
                        tv_expressage.setText("快递: ¥" + Double.valueOf(goods.getGoods().getGoodsKtpay()) / 100);
                        tv_sales_volume.setText("销量:" + goods.getGoods().getGoodsNum());
                        for (MainData mainData : list) {
                            if (goods.getGoods().getProvinceId().equals(mainData.getId())) {
                                tv_address.setText("地址:" + mainData.getTitle());
                            }
                        }

                        tv_stock.setText("库存:" + goods.getGoods().getGoodsStock());
                        tv_context.setText(goods.getGoods().getGoodsContext());

                        if (goods.getGoods().getGoodsSize() == null || "".equals(goods.getGoods().getGoodsSize())) {
                        } else {
                            tv_specification.setText(goods.getGoods().getGoodsSize());
                        }
                        tv_store_title.setText(goods.getShopName());
                        if (goods.getShopImage() != null || !"".equals(goods.getShopImage())) {
                            ImageUtils.imageRound(ShoppingDetailsActivity.this, goods.getShopImage(), iv_store_image);
                        }
                        if (goods.getContextNum() == 0) {
                            ll_comment.setVisibility(View.GONE);
                            tv_is_no_comment.setVisibility(View.VISIBLE);
                        } else {
                            ll_comment.setVisibility(View.VISIBLE);
                            tv_is_no_comment.setVisibility(View.GONE);
                            tv_evaluate.setText("宝贝评价(" + goods.getContextNum() + ")");
                            if (null != goods.getContext().getAvatarurl() || !"".equals(goods.getContext().getAvatarurl())) {
                                ImageUtils.imageCircle(ShoppingDetailsActivity.this, goods.getContext().getAvatarurl(), iv_photo_user);
                            }
                            tv_content.setText(goods.getContext().getContext());
                            tv_user_name.setText(goods.getContext().getNickname());
                        }
                        if (goodsData.getGoods().getGoodsMusic() != null && !"".equals(goodsData.getGoods().getGoodsMusic())) {
                            setAnim();
//                            operatingAnim = AnimationUtils.loadAnimation(ShoppingDetailsActivity.this, R.anim.rotate_anim);
//                            if (operatingAnim != null) {
//                                iv_image_music.startAnimation(operatingAnim);
//                            } else {
//                                iv_image_music.setAnimation(operatingAnim);
//                                iv_image_music.startAnimation(operatingAnim);
//                            }
                            isOpen = true;
                            initMediaPlayer(goodsData.getGoods().getGoodsMusic());
                        } else {
                            isOpen = false;
                        }
                        loadingDialog.dismiss();
                    }

                });


    }

    private void setAnim() {
        animator = ObjectAnimator.ofFloat(iv_image_music, "rotation", 0f, 360f);
        LinearInterpolator lin = new LinearInterpolator();
        animator.setInterpolator(lin);
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                if (isPans) {
                    setAnim();
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animator.setDuration(1500);
        animator.start();
    }

    private void initListener() {

    }

//    public class BannerViewFactory implements BannerView.ViewFactory<String> {
//
//        @Override
//        public View create(final String url, int position, ViewGroup container) {
//
//            if (!url.contains(".mp4")) {
//                ImageView iv = new ImageView(container.getContext());
//                ImageUtils.image(ShoppingDetailsActivity.this, url, iv);
//                return iv;
//            } else {
//                JZVideoPlayerStandard jzVideoPlayerStandard = new JZVideoPlayerStandard(ShoppingDetailsActivity.this);
//                jzVideoPlayerStandard.setUp(url, JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL);
//                ImageUtils.images(ShoppingDetailsActivity.this, url, jzVideoPlayerStandard.thumbImageView);
//                JZVideoPlayer.setJzUserAction(null);
//                return jzVideoPlayerStandard;
//            }
//        }
//
//    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onPause() {
        super.onPause();
        isPlayer = false;
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            }
        }
    }
    private ClipboardManager myClipboard;
    private ClipData myClip;

    @OnClick(R.id.tv_music)
    void music() {
//        if(goodsData.getShopTitle())
        myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        myClip = ClipData.newPlainText("text", goodsData.getWxChat());
        myClipboard.setPrimaryClip(myClip);
        ToastUtils.showLongToast("微信号已复制,请添加好友");
        ComponentName componet = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
        //pkg 就是第三方应用的包名
        //cls 就是第三方应用的进入的第一个Activity
        Intent intent = new Intent();
        intent.setComponent(componet);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @OnClick(R.id.tv_look_evaluate)
    void evaluate() {

    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    @OnClick(R.id.ll_store)
    void storeList() {
        startActivitys(StoreListActivity.class, goodsData.getShopId());
    }

    @OnClick(R.id.tv_kf_phone)
    void phone() {
        DialogUtils.dialog(this, "商家电话：" + goodsData.getShopTitle());
        DialogUtils.getTv_sure().setText("拨号");
        DialogUtils.getTv_sure().setOnClickListener(v -> {
            if (EasyPermissions.hasPermissions(this, perms)) {//检查是否获取该权限
                ToolPhone.callPhone(this, goodsData.getShopTitle());
                DialogUtils.dismissDialog();
            } else {
                //第二个参数是被拒绝后再次申请该权限的解释
                //第三个参数是请求码
                //第四个参数是要申请的权限
                EasyPermissions.requestPermissions(this, "必要的权限", 0, perms);
            }
        });

    }

    @OnClick(R.id.tv_store)
    void store() {
        startActivitys(StoreListActivity.class, goodsData.getShopId());
    }

    @OnClick(R.id.add_car)
    void addCar() {
        if (userInfo == null) {
            startActivitys(LoginActivity.class, 1);
            return;
        }

        if (goodsData.getGoods().getGoodsNo() != null && !goodsData.getGoods().getGoodsNo().equals("")) {
            if (goodsData.getGoods().getGoodsNo().equals("19949413191")) {
                ToastUtils.showShortToast("该商品不能添加购物车");
                return;
            }
        }
        loadingDialog.show();
        Map<String, String> map = new HashMap<>();
        map.put("token", userInfo.getToken());
        map.put("goodsId", shopping);
        map.put("num", 1 + "");
        RetrofitClient.getInstance(this)
                .createBaseApi()
                .addCar(map, new BaseSubscriber<ResponseBody>(this) {
                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable e) {
                        ToastUtils.showShortToast("网络错误");
                        loadingDialog.dismiss();
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        super.onNext(responseBody);
                        loadingDialog.dismiss();
                        try {
                            String request = responseBody.string();
                            JSONObject json = new JSONObject(request);
                            int status = json.getInt("code");
                            if (status == 0) {
                                ToastUtils.showShortToast(json.getString("message"));
                            } else {
                                ToastUtils.showShortToast(json.getString("message"));
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    @OnClick(R.id.tv_order)
    void order() {
        if (userInfo == null) {
            startActivitys(LoginActivity.class, 1);
            return;
        }
        if (goodsData.getGoods().getGoodsNo() != null && !goodsData.getGoods().getGoodsNo().equals("")) {
            if (goodsData.getGoods().getGoodsNo().equals("19949413191")) {
                intoOrder();
            } else {
                ChooseNum();
            }
        } else {
            ChooseNum();
        }
    }

    private void ChooseNum() {
        View v = getLayoutInflater().inflate(R.layout.layout_choose, null);
        final Dialog dialog = new Dialog(this, R.style.MyDialog);
        WindowManager wm = getWindowManager();
        int mHeight = wm.getDefaultDisplay().getHeight();
        int mWeight = wm.getDefaultDisplay().getWidth();
        dialog.setContentView(v, new WindowManager.LayoutParams(mWeight, ((mHeight * 2) / 3)));

        ImageView iv_subtract = v.findViewById(R.id.iv_choose_subtract);
        tv_num = v.findViewById(R.id.tv_choose_num);
        ImageView iv_add = v.findViewById(R.id.iv_choose_add);
        TextView tv_sure = v.findViewById(R.id.tv_sure);
        TextView tv_cancle = v.findViewById(R.id.tv_cancle);
        tv_num.setText(String.valueOf(num));

        iv_add.setOnClickListener(view -> add());
        iv_subtract.setOnClickListener(view -> subtract());
        tv_cancle.setOnClickListener(view -> dialog.dismiss());
        tv_sure.setOnClickListener(view -> {
            if (null == goodsData.getGoods().getGoodsLimit()) {
                intoOrder();
            } else {
                if (goodsData.getGoods().getGoodsLimit() >= num) {
                    intoOrder();
                } else {
                    ToastUtils.showShortToast("购买商品超出限购数量");
                }
            }
            dialog.dismiss();
        });

        Window window = dialog.getWindow();
        // 显示动画
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        dialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    private void intoOrder() {
        ArrayList<CarData> carDataList = new ArrayList<>();
        ArrayList<ShoppingcarDto> goodsList = new ArrayList<>();
        CarData myCarData = new CarData();
        Shop shop = new Shop();
        ShoppingcarDto shoppingcarDto = new ShoppingcarDto();
        shoppingcarDto.setSize(num);
        shoppingcarDto.setGoodsKtpay(goodsData.getGoods().getGoodsKtpay());
        shoppingcarDto.setGoodsImage(goodsData.getGoods().getGoodsImage());
        shoppingcarDto.setGoodsId(goodsData.getGoods().getGoodsId());
        shoppingcarDto.setGoodsName(goodsData.getGoods().getGoodsName());
        shoppingcarDto.setGoodsPay(goodsData.getGoods().getGoodsPay());
        shop.setShopId(goodsData.getShopId());
        shop.setShopName(goodsData.getShopName());
        shop.setShopImage(goodsData.getShopImage());
        goodsList.add(shoppingcarDto);
        myCarData.setList(goodsList);
        myCarData.setShop(shop);
        carDataList.add(myCarData);
        Intent intent = new Intent(this, MakeOrderActivity.class);
        intent.putExtra("carDataList", carDataList);
        intent.putExtra("type", 1);
        startActivity(intent);
    }

    // 减
    private void subtract() {
        if (num == 1) {
            ToastUtils.showShortToast("至少购买一件商品");
        } else {
            num--;
            tv_num.setText(String.valueOf(num));
        }
    }

    // 加
    private void add() {
        num++;
        tv_num.setText(String.valueOf(num));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (goodsData != null) {
                        if (null != goodsData.getGoods().getGoodsMusic() || !"".equals(goodsData.getGoods().getGoodsMusic())) {
                            initMediaPlayer(goodsData.getGoods().getGoodsMusic());
                        }
                    }

                } else {
                    ToastUtils.showShortToast("拒绝权限，将无法使用程序。");
                }
                break;
            default:
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }

}
